/*
 *       Copyright (c) 2008-2009 All rights reserved
 *               Asemantics S.r.l
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        Asemantics S.r.l."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    This product includes software developed by Asemantics S.r.l.
 *    the Semantic Web company, Rome, London, Leiden and its contributors.
 *
 * 5. Neither the name of the company nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


package com.asemantics.poco.persistence;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import org.apache.log4j.Logger;

import com.asemantics.poco.DateTime;
import com.asemantics.poco.Entry;
import com.asemantics.poco.query.Filter;
import com.asemantics.poco.query.FilterOp;
import com.asemantics.poco.query.Pagination;
import com.asemantics.poco.query.Query;
import com.asemantics.poco.query.SortOrder;
import com.asemantics.poco.query.Sorting;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

/**
 * @author Michele Mostarda ( michele.mostarda@gmail.com )
 */
public class EntriesByQueryTestCase {

    private final Logger LOGGER = Logger.getLogger( this.getClass() );

    /**
     * Internal persistor.
     */
    private Persistor persistor;

    /**
     * Entry ID used to to perform the #testRetrieveEntry. 
     */
    private String firstEntryID;

    @BeforeClass
    public void setUp() throws ConfigurationException {
        Configuration testConfiguration = Configuration.createConfiguration("/datanucleus.properties");
        persistor = new PersitorDefaultImpl( testConfiguration );
    }

    @AfterClass
    public void tearDown() {
        persistor = null;
    }

    /**
     * Tests the Persistor#retrieveEntries() method.
     *
     * @throws PersistorException
     * @throws QueryAdapterException
     */
    @Test
    public void testRetrieveEntries() throws PersistorException, QueryAdapterException {
        List<Entry> entries = persistor.retrieveEntries(createQueryCriteria(), true);
        assert entries.size() > 0 : "Expected some entries here.";

        // Some logging.
        for(Entry entry : entries) {
            LOGGER.debug("Retrieved entry: " + entry);
        }
        LOGGER.debug("Number of retrieved entries: " + entries.size());

        // Storing ID of first entry.
        firstEntryID = entries.get(0).getId();
    }

    /**
     * Tests the Persistor#retrieveEntry() method.
     *
     * @throws PersistorException
     * @throws QueryAdapterException
     */
    @Test(dependsOnMethods = {"testRetrieveEntries"})
    public void testRetrieveEntry() throws PersistorException, QueryAdapterException {
        Query query = createQueryCriteria();
        query.setPagination( new Pagination(0,10) );
        List<Entry> entries = persistor.retrieveEntry( firstEntryID, query, true );
        assert entries.size() == 1 : "Expected one entry for ID: " + firstEntryID;
        assert firstEntryID.equals( entries.get(0).getId() ) : "Unspected ID value.";
    }

    /**
     * Tests the Persistor#retrieveEntries() method.
     * 
     * @throws PersistorException
     * @throws QueryAdapterException
     */
    @Test(dependsOnMethods = {"testRetrieveEntries"})
    public void testRetrieveEntriesOf() throws PersistorException, QueryAdapterException {
        Query query = createQueryCriteria();
        query.setPagination( new Pagination(0,10) );
        List<Entry> entries = persistor.retrieveEntriesOf( firstEntryID, query, true );
        assert entries.size() == 1 : "Expected exaclty on contact for entry with ID: " + firstEntryID;
    }

    /**
     * Creates the query criteria.
     * 
     * @return
     */
    private Query createQueryCriteria() {
        Query query = new Query();
        // sorting.
        query.setSorting( new Sorting("id", SortOrder.ascending) );
        // pagination.
        query.setPagination( new Pagination(1, 5) ); // begin, count
        // Filtering.
        Calendar calendar = new GregorianCalendar(2008, GregorianCalendar.JANUARY, 1, 1, 1, 1);
        query.setFilter(
                new Filter(
                        "note",
                        FilterOp.contains,
                        "declare",
                        new DateTime(calendar.getTime(), TimeZone.getDefault())
                )
        );
        return query;
    }

}
